/**
 * create by young (young2f@outlook.com) on 2020/9/12
 */


'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {DatePicker, Drawer, Form, Input, Select, Table, Tabs} from 'antd';

import styles from '../index.less';
import ViewTitle from '../../components/ViewTitle';
import FormBase from '../../components/Base/FormBase';
import notify from "../../components/NotificationExtra";
import {FormField, SearchForm} from 'antd-extra';
import moment from 'moment';
import 'moment/locale/zh-cn';
import ModalOutboundOrderDetail from "./modal/ModalOutboundOrderDetail";
import ProcureReturnOfGoods from "./tabs/ProcureReturnOfGoods";

moment.locale('zh-cn');
const {RangePicker} = DatePicker;
const _ = require('lodash');
const {Option} = Select;
const table = 'OutboundOrder';
const title = '出库单';

@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            customer,
            sales,
            dict,
            material,
            store
          }) => ({...user, ...global, ...dict, ...material, ...customer, ...sales, ...store, ...dynamicLabel}))
export default class OutboundOrder extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  getSearchPayload() {
    const data = this.props.form.getFieldsValue();
    let {
      customer,
      code,
      contacts,
      contactsPhone,
      reviewStatus,
      prodName,
      material,
      isInvoice,
      createdTs,
      division,
      deliverWay
    } = data;

    const start = createdTs && createdTs.length === 2 ? createdTs[0] : undefined;
    const end = createdTs && createdTs.length === 2 ? createdTs[1] : undefined;
    // const invoiceStart = invoiceTime && invoiceTime.length === 2 ? invoiceTime[0] : undefined;
    // const invoiceEnd = invoiceTime && invoiceTime.length === 2 ? invoiceTime[1] : undefined;
    if (reviewStatus) {
      reviewStatus = reviewStatus === 0 ? undefined : reviewStatus;
      reviewStatus = reviewStatus === 1 ? '待审核' : reviewStatus;
      reviewStatus = reviewStatus === 2 ? '同意' : reviewStatus;
      reviewStatus = reviewStatus === 3 ? '驳回' : reviewStatus;
    }
    /**
     * 输入框清除之后会成为 ”“
     * @type {undefined}
     */
    customer = customer === '' ? undefined : customer;
    contactsPhone = contactsPhone === '' ? undefined : contactsPhone;
    contacts = contacts === '' ? undefined : contacts;
    division = division === '' ? undefined : division;

    code = code === '' ? undefined : code;
    prodName = prodName === '' ? undefined : prodName;

    return {
      customer,
      code,
      division,
      reviewStatus,
      start,
      end,
      prodName,
      material,
      isInvoice,
      contacts,
      contactsPhone,
      "prods.deliverWay": deliverWay
    };
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const data = this.props.form.getFieldsValue();
    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table, tenantCode: this.getTenantCode()}
    });

    this.props.dispatch({
      type: 'sales/findMany',
      payload: {...data}
    });
    dispatch && dispatch({
      type: 'dict/findMany',
      payload: {type: 'division', tenantCode: this.getTenantCode()}
    });
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'material/findMany',
      payload: {}
    });
  }


  getTableCols = () => {
    const model = this.props[`${table}Model`];
    if (!model) return [];
    const temp = [];
    _.map(model, (item, key) => {
      const {enableArea, title, _type} = item;
      if (_.includes(enableArea, "table")) {
        item.title = title;
        item.key = key;
        item.dataIndex = key;
        _type === 'switch' ? item.render = (record) => {
          const value = record ? "是" : "否";
          return <div>{value}</div>;
        } : undefined;
        temp.push(item);
      }
    });
    //  temp = _.concat(temp, temp1)
    temp.push(
      {
        title: '创建者',
        dataIndex: 'createUsername',
        key: 'createUsername',
        width: 120
      },
      {
        title: '创建时间',
        dataIndex: 'createdTs',
        key: 'createdTs',
        width: 160,
        render: value => {
          return <div>{moment(value).format('YYYY-MM-DD hh:mm:ss')}</div>;
        }
      },
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 160, fixed: 'right',
        render: (value, record) => {
          return (
            <a style={{marginRight: '6px'}}
               onClick={() => this.setState({showDetail: true, record})}>详情</a>

          );
        }
      });
    return temp;

  };
  getSearchFields = () => {
    const {divisionDict} = this.props;
    const arr = [
      <FormField
        label="订单编码"
        name="code"
        key={1}
      >
        <Input allowClear placeholder={`请输入${title}编码`}/>
      </FormField>,

      <FormField
        label="客户"
        name="customer"
        key={3}
      >
        <Input allowClear placeholder="请输入客户"/>
      </FormField>,
      <FormField
        label="联系人"
        name="contacts"
        key={4}
      >
        <Input allowClear placeholder="请输入联系人"/>
      </FormField>,
      <FormField
        label="联系人号码"
        name="contactsPhone"
        key={5}
      >
        <Input allowClear placeholder="请输入联系人号码"/>
      </FormField>,
      <FormField
        label="品名"
        name="prods.prodName"
        key={6}
      >
        <Input allowClear placeholder="请输入品名"/>
      </FormField>,


      // <FormField
      //   label="开票时间"
      //   name="invoiceTime"
      //   key={12}
      //
      // >
      //   <RangePicker allowClear={true}
      //     // style={{ width: '150%' }}
      //   />
      // </FormField>,
      <FormField
        label="销售公司"
        name="division"
        key={8}
      >
        <Select allowClear placeholder="请选择" showSearch
                filterOption={(input, option) =>
                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
        >
          {this.getDivision(divisionDict)}
        </Select>
      </FormField>,
      <FormField
        label="发货方式"
        name="prods.deliverWay"
        key={9}
      >
        <Select allowClear placeholder="请选择">
          <Option value={'直发'}>{'直发'}</Option>
          <Option value={'仓库'}>{'仓库'}</Option>
          <Option value={'业务员送'}>{'业务员送'}</Option>
          <Option value={'客户自提'}>{'客户自提'}</Option>
        </Select>
      </FormField>,

      <FormField
        label="创建时间"
        name="createdTs"
        key={10}
        initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
      >
        <RangePicker allowClear={true}
          // style={{ width: '150%' }}
        />
      </FormField>,
      <FormField
        label="审核状态"
        name="reviewStatus"
        key={11}
      >
        <Select allowClear placeholder="请选择">
          <Option value={1}>{'待审核'}</Option>
          <Option value={2}>{'同意'}</Option>
          <Option value={3}>{'驳回'}</Option>
        </Select>
      </FormField>
    ];
    return arr;

  };


  render() {
    const {sales = {}, _notify, form, dispatch} = this.props;
    const {record = {}, showDetail} = this.state;

    const {array = []} = sales;
    if (_notify && this.state._notify !== _notify) {
      notify(_notify);
      this.state._notify = _notify;
    }
    return (
      <Form className={styles.content}>
        <Tabs defaultActiveKey={'1'}>
          <Tabs.TabPane tab={'订单发货出库'} key="1">
            <ViewTitle
              title={`订单出货列表`}
              level={1}
            ></ViewTitle>
            <SearchForm
              style={{marginLeft: '6px', marginRight: '6px'}}
              onSearch={() => {
                this.state.current = 1;
                this.componentDidMount();
              }}
              onReset={this.handleReset}
              cols={4}
              min={8}
              expandText="展开"
              form={form}
            >
              {this.getSearchFields()}
            </SearchForm>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.getTableCols()}
              dataSource={array}
              scroll={{x: true}}
              pagination={true}
              //  scroll={{ x: 1300 }}
            ></Table>

            {showDetail && <Drawer
              visible={showDetail}
              title={`${title}详情`}
              placement="left"
              width={'80%'}
              style={{padding: 0}}
              // maskClosable={false}
              onClose={() => {
                this.setState({showDetail: false});
                this.componentDidMount();
              }}
            >
              <ModalOutboundOrderDetail
                values={record}
              > </ModalOutboundOrderDetail>
            </Drawer>}
          </Tabs.TabPane>
          <Tabs.TabPane tab={'采购退货出库'} key={'2'}>
            <ProcureReturnOfGoods></ProcureReturnOfGoods>
          </Tabs.TabPane>
        </Tabs>
      </Form>
    );
  }
}


